package cn.cvs.controller;

import cn.cvs.pojo.SysUser;
import cn.cvs.service.SysUserService;
import cn.cvs.utils.TableVO;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private SysUserService sysUserService;

    @GetMapping("/list2")
    public String list2(){
        return "sysUser/list";
    }

    @GetMapping("/addPage")
    public String addPage(){
        return "/view/system/sysUser/add";
    }

    @GetMapping("/updates/{id}")
    public String updates(Model model,@PathVariable Integer id){

        SysUser sysUser = sysUserService.queryById(id);

        model.addAttribute("sysUser",sysUser);

        return "/view/system/sysUser/update";
    }

    @GetMapping(value = "/list",produces = {"application/json;charset=utf-8"})
    @ResponseBody
    public String list(Integer page,Integer limit,String loginName,String phonenumber,Integer deptId) {

        List<SysUser> list = sysUserService.list(page,limit,loginName,phonenumber,deptId);

        int count = sysUserService.count(loginName,phonenumber,deptId);

        TableVO tableVO = new TableVO(0, count, list, "");

        String json = JSON.toJSONString(tableVO);

        return json;
    }

    @GetMapping("/delete/{userId}")
    @ResponseBody
    public String delete(@PathVariable Integer userId){

        int delete = sysUserService.delete(userId);

        if (delete < 1) {
            return "0";
        }
        return "1";
    }

    /**
     * 该方法需要用事务，暂时先写死
     */
    @GetMapping("/deletes/{id}")
    @ResponseBody
    public String deletes(@PathVariable String id){

        String[] ids = id.split(",");

        for (int i = 0; i < ids.length; i++) {
            sysUserService.delete(Integer.parseInt(ids[i]));
        }

        return "1";
    }

    @RequestMapping(value = "/add",method = RequestMethod.POST)
    @ResponseBody
    public String add(SysUser sysUser){
        int count= sysUserService.add(sysUser);

        if (count>0){
            return "true";
        }
        return "false";
    }

    @RequestMapping(value = "/update",method = RequestMethod.POST)
    @ResponseBody
    public String update(SysUser sysUser){
        int count = sysUserService.update(sysUser);

        if (count>0){
            return "true";
        }

        return "false";
    }

    @GetMapping("/status")
    public String changeStatus(Integer id,char status){

        int i = sysUserService.changeStatus(id,status);

        if (i > 0){
            return "true";
        }

        return "false";
    }

}
